package com.netty.modbus.util;

import com.netty.modbus.dto.request.CommonBody;
import com.netty.modbus.dto.request.ReadBody;
import com.netty.modbus.dto.request.RequestBody;
import com.netty.modbus.dto.request.WriteBody;
import com.netty.modbus.repository.DevChannelRepository;
import io.netty.channel.Channel;

/**
 * description: SendCommand <br>
 * @date: 2021/10/9 9:57 <br>
 * @author: lwy <br>
 * @version: 1.0 <br>
 */
public class SendCommand {
    private static DevChannelRepository devChannelRepository=DevChannelRepository.getInstance();

    /**
     * description: 发送读命令
     * version: 1.0
     * date: 2021/10/9 10:23
     * @author: lwy
     * @param devNumber 设备编码
     * @param startPosHex 起始寄存器位置16进制
     * @param quantityHex 寄存器数量16进制
     * @return void
     */
    public static void sendReadCommand(String devNumber,String startPosHex,String quantityHex) throws Exception {
        //封装请求体
        ReadBody readBody=new ReadBody(HexUtil.hexToBytes(startPosHex),HexUtil.hexToBytes(quantityHex));
        readBody.setDevNumber(devNumber);
        //发送请求
        sendCommand(devNumber,readBody);
    }
    /**
     * description: 发送修改命令
     * version: 1.0
     * date: 2021/10/18 11:48
     * @author: lwy
     * @param devNumber 设备编唯一号
     * @param startPosHex 开始修改寄存器位置
     * @param quantityHex 修改寄存器数量
     * @param quantity1Hex 修改字节数
     * @param dataHex 修改数据
     * @return void
     */
    public static void sendWriteCommand(String devNumber,String startPosHex,String quantityHex,String quantity1Hex,String dataHex) throws Exception {
        //封装请求体
        WriteBody writeBody=new WriteBody(
                HexUtil.hexToBytes(startPosHex),
                HexUtil.hexToBytes(quantityHex),
                HexUtil.hexToByte(quantity1Hex),
                HexUtil.hexToBytes(dataHex)
        );
        writeBody.setDevNumber(devNumber);
        sendCommand(devNumber,writeBody);
    }

    /**
     * description: 发送常用命令
     * version: 1.0
     * date: 2021/10/18 13:48
     * @author: lwy
     * @param devNumber 设备编号
     * @param commonCommandHex 常用命令，直接转成byte[]发送
     * @return void
     */
    public static void sendCommonCommand(String devNumber,String commonCommandHex) throws Exception {
        CommonBody commonBody=new CommonBody(devNumber,commonCommandHex);
        SendCommand.sendCommand(devNumber,commonBody);
    }



    /**
     * description: 发送自定义读写命令
     * version: 1.0
     * date: 2021/10/18 11:50
     * @author: lwy
     * @param devNumber 设备编号
     * @param requestBody 发送消息体
     * @return void
     */
    private static void sendCommand(String devNumber,RequestBody requestBody) throws Exception {
        //该设备的通道
        Channel channel=devChannelRepository.getDevChannel().get(devNumber);
        if(channel==null){
            throw new Exception("未查询到设备");
        }
        //发送请求
        channel.write(requestBody);
    }




}
